<?php

namespace app\kernel;

use app\kernel\service\Service as BaseService;
use think\App;
use Workerman\Worker;

class Cmd
{

    /**
     * @var App $app
     */
    protected $app;

    /**
     * @var string
     */
    protected $process;


    public function __construct(App $app)
    {

        $this->app = $app;
        $this->initialize();

        $this->process = $this->app->getAppPath() . 'process.php';

    }

    /**
     * 初始化
     */
    protected function initialize()
    {
        //
        if (!$this->app->initialized()) {
            $this->app->initialize();
        }
        Worker::$pidFile = $this->app->getRuntimePath() . 'cmd.pid';
        Worker::$stdoutFile = $this->app->getRuntimePath() . 'cmd-stdout.log';
        Worker::$logFile = $this->app->getRuntimePath() . 'log/cmd-work.log';

    }



    /**
     * 开始
     * @return void
     */
    public function run()
    {

        if (!file_exists($this->process)) {
            return;
        }

        $process = include $this->process;
        foreach ($process as $item) {

            if (!class_exists($item)) {
                continue;
            }
            $item = new $item($this->app);
            if (!$item instanceof BaseService) {
                continue;
            }
            $item->register();
        }
        Worker::runAll();
    }

}